package cn.chiship.framework.docs.biz.controller;


import cn.chiship.framework.docs.biz.pojo.dto.ChunkMultipartFileParam;
import cn.chiship.framework.docs.biz.service.FileResourcesService;
import cn.chiship.framework.docs.biz.service.FileService;
import cn.chiship.sdk.cache.vo.CacheUserVO;
import cn.chiship.sdk.core.annotation.NoParamsSign;
import cn.chiship.sdk.core.annotation.NoVerificationAppIdAndKey;
import cn.chiship.sdk.core.base.BaseResult;
import cn.chiship.sdk.core.util.StringUtil;
import cn.chiship.framework.common.annotation.LoginUser;

import cn.chiship.framework.docs.core.properties.FileUploadProperties;
import cn.chiship.sdk.framework.multipartFile.Base64ToMultipartFile;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.Map;

/**
 * @author lijian
 */

/**
 * @author lijian
 */
@RequestMapping("/file")
@Api(tags = "文件上传控制器")
@NoVerificationAppIdAndKey
@RestController
public class UploadController {
    @Resource
    FileService fileService;
    @Resource
    FileResourcesService fileResourcesService;

    @Resource
    FileUploadProperties fileUploadProperties;


    /**
     * 处理文件上传POST请求
     * 将上传的文件存放到服务器内
     *
     * @param chunk    文件块
     * @param response 响应
     * @return 上传响应状态
     */
    @ApiOperation(value = "文件分片上传")
    @PostMapping("/chunkUpload")
    @NoParamsSign
    public ResponseEntity chunkUploadPost(@ModelAttribute ChunkMultipartFileParam chunk, HttpServletResponse response) {
        return new ResponseEntity(fileService.chunkUploadPost(chunk, response), HttpStatus.OK);
    }

    /**
     * 处理文件上传GET请求
     * 验证上传的文件块，是否允许浏览器再次发送POST请求（携带二进制文件的请求流，FormData）
     *
     * @return 文件块
     */
    @ApiOperation(value = "验证文件分片上传否允许浏览器再次发送POST请求")
    @GetMapping("/chunkUpload")
    @NoParamsSign
    public ResponseEntity chunkUploadGet(@ModelAttribute ChunkMultipartFileParam chunk) {
        return new ResponseEntity(fileService.chunkUploadGet(chunk), HttpStatus.OK);
    }

    @ApiOperation(value = "文件分片上传合并")
    @PostMapping("chunksMerge")
    @NoParamsSign
    public ResponseEntity<BaseResult> chunksMerge(@RequestBody @Valid ChunkMultipartFileParam chunk, @ApiIgnore @LoginUser CacheUserVO userVO) {
        String catalogId = chunk.getCatalogId();
        if (StringUtil.isNullOrEmpty(catalogId)) {
            return new ResponseEntity<>(BaseResult.error("缺少参数[catalogId]"), HttpStatus.OK);
        }
        if (StringUtil.isNullOrEmpty(fileUploadProperties.getFilePathByCatalogId(catalogId))) {
            return new ResponseEntity<>(BaseResult.error("参数[catalogId]不存在,请核对"), HttpStatus.OK);
        }
        return new ResponseEntity<>(fileService.mergeFile(chunk, userVO), HttpStatus.OK);
    }


    @ApiOperation(value = "文件上传")
    @PostMapping("/upload")
    @NoParamsSign
    public ResponseEntity<BaseResult> upload(HttpServletRequest request, @RequestParam("file") MultipartFile file, @ApiIgnore @LoginUser CacheUserVO userVO) throws Exception {
        String catalogId = request.getParameter("catalogId");
        return multipartFileUpload(catalogId, file, userVO);
    }

    @ApiOperation(value = "base64图片上传（body）")
    @PostMapping("/base64Upload")
    @NoParamsSign
    public ResponseEntity<BaseResult> pictureUpload(@RequestBody Map<String, String> map, @ApiIgnore @LoginUser CacheUserVO userVO) throws Exception {
        String catalogId = map.get("catalogId");
        MultipartFile file = Base64ToMultipartFile.base64Convert(map.get("base64"));
        return multipartFileUpload(catalogId, file, userVO);
    }

    @ApiOperation(value = "base64图片上传（Form）")
    @PostMapping("/base64UploadForm")
    @NoParamsSign
    public ResponseEntity<BaseResult> base64UploadForm(HttpServletRequest request, String base64, @ApiIgnore @LoginUser CacheUserVO userVO) throws Exception {
        String catalogId = request.getParameter("catalogId");
        MultipartFile file = Base64ToMultipartFile.base64Convert(base64);
        return multipartFileUpload(catalogId, file, userVO);
    }

    private ResponseEntity<BaseResult> multipartFileUpload(String catalogId, MultipartFile file, CacheUserVO userVO) throws IOException {
        BaseResult baseResult = fileResourcesService.uploadFile(file, catalogId, userVO);
        return new ResponseEntity<>(baseResult, HttpStatus.OK);
    }
}